在React中,state是不可以被修改的,我们可以使用Immutable来帮助我们更好的实现这一项
安装1
npm install immutable
common/header/store/reducer.js1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import * as constants from './constants'
// 导入immutable
import { fromJS } from 'immutable'
// 创建immutable对象
const defaultState = fromJS({
'inputValue': ''
});
export default (state = defaultState, action ) => {
if (action.type === constants.SEARCH_FOCUS){
// return {
// inputValue: '测试文本'
// }
// immutable对象的set方法,会结合之前的immutable对象的值和设置的值,返回一个全新的对象
return state.set('inputValue', '测试文本')
}
return state;
}
common/header/index.js1
2
3
4
5
6const mapStateToProps = (state) => {
return {
// 这里因为使用了immutable,所以state.header是一个immutable对象,我们在获取值的时候就需要使用get方法。
inputValue: state.header.get('inputValue')
}
}